package me.panpf.sketch.optionsfilter;

import me.panpf.sketch.Configuration;
import me.panpf.sketch.util.Log;
import ohos.app.Context;
import ohos.net.NetCapabilities;
import ohos.net.NetHandle;
import ohos.net.NetManager;
import ohos.net.NetStatusCallback;

import java.lang.ref.WeakReference;


/**
 * 全局移动数据或有流量限制的 WIFI 下暂停下载控制器
 */
@SuppressWarnings("WeakerAccess")
public class MobileDataPauseDownloadController {
    private DefaultNetStatusCallback receiver;
    private boolean opened;
    private Configuration configuration;
    private NetManager netManager;

    public MobileDataPauseDownloadController(Configuration configuration) {
        netManager = NetManager.getInstance(configuration.getContext());
        receiver = new DefaultNetStatusCallback(configuration.getContext(), this);
        this.configuration = configuration;
    }

    /**
     * 已经开启了？
     * @return boolean
     */
    public boolean isOpened() {
        return opened;
    }

    /**
     * 开启功能
     *
     * @param opened 开启
     */
    public void setOpened(boolean opened) {
        if (this.opened == opened) {
            return;
        }
        this.opened = opened;

        if (this.opened) {
            updateStatus(receiver.context);
            netManager.addDefaultNetStatusCallback(receiver);
//            receiver.register();
        } else {
            configuration.setPauseDownloadEnabled(false);
//            receiver.unregister();
            netManager.removeNetStatusCallback(receiver);
        }
    }

    /**
     * 网络状态变化或初始化时更新全局暂停功能
     *
     * @param context {@link Context}
     */
    private void updateStatus(Context context) {
        NetManager netManager = NetManager.getInstance(context);
        NetCapabilities netCapabilities = netManager.getNetCapabilities(netManager.getDefaultNet());
//        ConnectivityManager connectivityManager = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE));
//        NetworkInfo networkInfo = connectivityManager != null ? connectivityManager.getActiveNetworkInfo() : null;
        boolean pause = false;
        if (netCapabilities != null && netCapabilities.hasCap(NetCapabilities.NET_CAPABILITY_VALIDATED)) {
            if (netCapabilities.hasCap(NetCapabilities.NET_CAPABILITY_VALIDATED) &&
                    netCapabilities.hasBearer(NetCapabilities.BEARER_CELLULAR)) {
                pause = true;
            }
//            else if (netCapabilities.hasBearer(NetCapabilities.BEARER_WIFI) ||
//                    netCapabilities.hasBearer(NetCapabilities.BEARER_WIFI_AWARE)) {
//                pause = true;
//            }
        }
        configuration.setPauseDownloadEnabled(pause);
    }

    public static final class DefaultNetStatusCallback extends NetStatusCallback {
        private Context context;
        private WeakReference<MobileDataPauseDownloadController> weakReference;

        public DefaultNetStatusCallback(Context context, MobileDataPauseDownloadController download) {
            this.context = context;
            this.weakReference = new WeakReference<>(download);
        }

        @Override
        public void onCapabilitiesChanged(NetHandle handle, NetCapabilities networkCapabilities) {
            super.onCapabilitiesChanged(handle, networkCapabilities);
            if (networkCapabilities.hasCap(NetCapabilities.NET_CAPABILITY_VALIDATED)) {
                // 网络连接成功，并且可以上网
                MobileDataPauseDownloadController pauseDownloadController = weakReference.get();
                if (pauseDownloadController != null) {
                    pauseDownloadController.updateStatus(context);
                }
            } else {

            }
        }
    }

//    /**
//     * 监听网络变化的广播
//     */
//    private static class NetworkChangedBroadcastReceiver extends CommonEventSubscriber {
//        private Context context;
//        private WeakReference<MobileDataPauseDownloadController> weakReference;
//
//        public NetworkChangedBroadcastReceiver(Context context, MobileDataPauseDownloadController download) {
//            this.context = context.getApplicationContext();
//            this.weakReference = new WeakReference<>(download);
//        }
//
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
//                MobileDataPauseDownloadController pauseDownloadController = weakReference.get();
//                if (pauseDownloadController != null) {
//                    pauseDownloadController.updateStatus(context);
//                }
//            }
//        }
//
//        private void register() {
//            try {
//                context.registerReceiver(this, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
//            } catch (IllegalArgumentException e) {
//                e.printStackTrace();
//            }
//        }
//
//        private void unregister() {
//            try {
//                context.unregisterReceiver(this);
//            } catch (IllegalArgumentException e) {
//                e.printStackTrace();
//            }
//        }
//    }
}
